﻿$(function () {
	$(window).on("scroll", LiveBlog.ScrollLoad);
	var lastItem = $("#Stream .item").last();
	LiveBlog.State = new LiveBlog.ContentState(lastItem.find(".postTime").attr("data-utc"), $("#OldestID").val(), lastItem.attr("data-contentItemID"));
	LiveBlog.startTimeUpdater();
});

var LiveBlog = {};

LiveBlog.State = null;

LiveBlog.ContentState = function (lastTime, oldestID, lastID) {
	this.lastTime = lastTime;
	this.oldestID = oldestID;
	this.lastID = lastID;
	this.isLoading = false;
};

LiveBlog.listen = function () {
	var hub = $.connection.mainHub;
	hub.client.notifyFeed = function (data) {
		var row = LiveBlog.update(data);
		$("#Stream").prepend(row);
	};
	$.connection.hub.start();
};

LiveBlog.update = function (data) {
	var row = $("#ContentTemplate").clone();
	row.removeClass("hide");
	row.removeAttr("id");
	row.attr("data-contentItemID", data.ContentItemID);
	row.find(".content").html(data.Content);
	row.find(".name").text(data.Name);
	row.find(".postTime").text(data.FormattedTime);
	row.find(".postTime").attr("data-utc", data.Utc);
	row.find("form").attr("action", "/admin/delete/" + data.ContentItemID);
	row.find(".stat a").attr("href", "/home/item/" + data.ContentItemID);
	return row;
};

LiveBlog.ScrollLoad = function () {
	var win = $(window);
	var streamEnd = $("#StreamBottom").offset().top;
	var viewEnd = win.scrollTop() + win.height();
	var distance = streamEnd - viewEnd;
	if (LiveBlog.State.oldestID != LiveBlog.State.lastID && !LiveBlog.State.isLoading && distance < 250) {
		LiveBlog.LoadMore();
	}
};

LiveBlog.LoadMore = function () {
	LiveBlog.State.isLoading = true;
	$.ajax({
		url: "/Home/GetMore",
		type: "POST",
		data: { lastTime: LiveBlog.State.lastTime },
		dataType: "json",
		success: function (result) {
			$.each(result, function () {
				var row = LiveBlog.update(this);
				$("#Stream").append(row);
				LiveBlog.State.lastTime = this.Utc;
				LiveBlog.State.lastID = this.ContentItemID.toString();
			});
			LiveBlog.State.isLoading = false;
		},
		error: function () {
			LiveBlog.State.isLoading = false;
			alert("There was an error getting more posts.");
		}
	});
};

LiveBlog.startTimeUpdater = function () {
	setTimeout(function () {
		LiveBlog.startTimeUpdater();
		LiveBlog.updateTimes();
	}, 60000);
};

LiveBlog.updateTimes = function () {
	var a = [];
	var times = $(".postTime");
	$.each(times, function () {
		var t = $(this).attr("data-utc");
		if (((new Date() - new Date(t + "Z")) / 3600000) < 48)
			a.push(t);
	});
	if (a.length > 0)
		$.ajax({
			url: "/Home/GetTimes",
			type: "POST",
			data: { times: a },
			dataType: "json",
			traditional: true,
			success: function (result) {
				$.each(result, function () {
					$(".postTime[data-utc='" + this.Key + "']").text(this.Value);
				});
			},
			error: function () {
			}
		});
};